<!-- 洁净室可视化模型 -->
<template>
  <div>
    <div class="page-main">
      <div class="header_box">
        <div class="top_box">
          <timeItem />
          <weatherTop />
        </div>
        <div class="switch_box">
          <div class="switch_tabs">
            <div
              v-for="(item, index) in areaData"
              :key="index"
              v-optimize:debounce="{ event: 'click', fn: () => tabsClick(item, index), timeout: 500 }"
              :class="activeIndex === index ? 'activeClass' : 'switch_item'"
            >
              <div class="item_name">{{ item.name }}</div>
              <!-- <div :class="[item.worningNum > 0 ? 'item_red' : 'item_green']">{{ item.worningNum || 0 }}</div> -->
            </div>
          </div>
        </div>
        <div class="top-con-check">
          <div class="check-btn-item">
            <div class="check-title">环境指标：</div>
            <div class="spc_target">
              <px-checkbox-group v-model="targetList">
                <px-checkbox v-for="item in environData" :key="item.id" disabled :label="item.type">{{ item.itemName }}</px-checkbox>
              </px-checkbox-group>
            </div>
          </div>
          <div class="check-btn-item">
            <div class="check-title">洁净指标：</div>
            <div class="spc_target">
              <px-checkbox-group v-model="targetList2">
                <px-checkbox v-for="item in particleData" :key="item.id" disabled :label="item.type">{{ item.itemName }}</px-checkbox>
              </px-checkbox-group>
            </div>
          </div>
          <div class="check-btn-item">
            <div class="check-title">AMC：</div>
            <div class="spc_target">
              <px-checkbox-group v-model="targetList3">
                <px-checkbox v-for="item in amcData" :key="item.id" disabled :label="item.type">{{ item.itemName }}</px-checkbox>
              </px-checkbox-group>
            </div>
          </div>
          <div class="check-btn-item">
            <div class="check-title">设备指标：</div>
            <div class="spc_target">
              <px-checkbox-group v-model="targetList4">
                <!-- <px-checkbox v-for="item in eqpData" :key="item.id" :label="item.type">{{ item.itemName }}</px-checkbox> -->
                <px-checkbox disabled :label="1">{{ mauSelectName }}</px-checkbox>
                <px-checkbox disabled :label="2">{{ dccSelectName }}</px-checkbox>
              </px-checkbox-group>
            </div>
          </div>
        </div>
        <px-form ref="querySpcRef" class="custom-form-ui inspection-form" :model="Detail" :inline="true">
          <px-form-item label="时间日期" style="width: 460px">
            <px-date-picker
              v-model="dateRangeSpc"
              :clearable="false"
              type="datetimerange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :defaultTime="defaultTime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </px-form-item>
          <px-form-item label="周期" prop="testCompany" style="width: 200px">
            <px-select v-model="Detail.testCompany" filterable placeholder="请选择周期" @change="handleQuerySpc">
              <px-option
                v-for="item in testCompanyList"
                :key="item.value"
                :disabled="item.value === '本月'"
                :label="item.label"
                :value="item.value"
              />
            </px-select>
          </px-form-item>
          <px-button v-optimize:debounce="{ event: 'click', fn: () => handleQuery(), timeout: 1000 }" type="primary" icon="">搜索</px-button>
          <px-button v-optimize:debounce="{ event: 'click', fn: () => resetQuery(), timeout: 1000 }" icon="">重置</px-button>
        </px-form>
      </div>
      <div class="small_map">
        <div class="map_img" :style="{ backgroundImage: `url(${currentMapImage})` }" />
      </div>
    </div>
    <div class="page-con-img">
      <div class="con_left" :style="{ width: showCharts ? '20%' : '100%' }">
        <MinimapPanel
          :image-src="currentBackgroundImage"
          :width="minimapImageSize.width"
          :height="minimapImageSize.height"
          :linesOptions="linesOptions"
          :showCharts="showCharts"
        >
          <!-- 2.5D-PID -->
          <div
            v-for="item in pointData"
            :key="item.point"
            :class="{ con_img_point: true, 'no-click': !isClick }"
            :style="{
              top: item.top,
              left: item.left
            }"
            @click="pointClick(item)"
          >
            <px-popover placement="top" width="auto" trigger="hover" :content="`${item.point}(${item.specName})`">
              <template #reference>
                <div
                  class="point_item"
                  :style="{
                    color: isActiveBtns.includes(item.point) ? 'white' : 'black',
                    backgroundColor: isActiveBtns.includes(item.point) ? '#3B82F6' : 'white'
                  }"
                >
                  <component :is="item.isAlarm ? iconComList['point_warning'] : iconComList[item?.icon]" class="content-icon color-total" />
                  <div class="point_name">{{ item?.iName }}:</div>
                  <div class="pop_value">{{ item?.iValue }}{{ item?.unit }}</div>
                </div>
              </template>
            </px-popover>
          </div>
          <!-- 洁净室指标-Q -->
          <div class="con_img_panel">
            <div class="panel_box">
              <div class="panel_title">洁净室指标-Q</div>
              <div class="panel_con">
                <div class="panel_con_left">
                  <div
                    v-for="item in particleBtnData"
                    :key="item.itemValue"
                    :style="{
                      cursor: 'pointer',
                      color: isActiveBtns.includes(item.point) ? 'white' : 'black',
                      backgroundColor: isActiveBtns.includes(item.point) ? '#3B82F6' : 'white'
                    }"
                  >
                    <px-popover :disabled="!item.point || !item.point.length" placement="top" width="auto" trigger="hover" :content="`${item.point}`">
                      <template #reference>
                        <div class="con_list">
                          <div class="list_left">{{ item.itemName }}:</div>
                          <div class="list_value">
                            {{ getValue(item.point, "currentValue") ? getValue(item.point, "currentValue") : "-"
                            }}{{ getUnit(item.itemValue, particleBtnData) }}
                          </div>
                        </div>
                      </template>
                    </px-popover>
                  </div>
                </div>
                <div style="width: 1px; background-color: #dcdcdc" />
                <div class="panel_con_right">
                  <div
                    v-for="item in amcBtnData"
                    :key="item.itemValue"
                    :style="{
                      cursor: 'pointer',
                      color: isActiveBtns.includes(item.point) ? 'white' : 'black',
                      backgroundColor: isActiveBtns.includes(item.point) ? '#3B82F6' : 'white'
                    }"
                  >
                    <px-popover :disabled="!item.point || !item.point.length" placement="top" width="auto" trigger="hover" :content="`${item.point}`">
                      <template #reference>
                        <div class="con_list">
                          <div class="list_left">{{ item.itemName }}:</div>
                          <div class="list_value">
                            {{ getValue(item.point, "currentValue") ? getValue(item.point, "currentValue") : "-"
                            }}{{ getUnit(item.itemValue, amcBtnData) }}
                          </div>
                        </div>
                      </template>
                    </px-popover>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </MinimapPanel>
        <!-- <div class="con_img" :style="{ backgroundImage: currentBackgroundImage }">
          <div
            v-for="item in pointData"
            :key="item.point"
            class="con_img_point"
            :style="{
              top: item.top,
              left: item.left
            }"
            @click="pointClick(item)"
          >
            <px-popover placement="top" width="auto" trigger="hover" :content="`${item.point}(${item.specName})`">
              <template #reference>
                <div
                  class="point_item"
                  :style="{
                    color: isActiveBtns.includes(item.point) ? 'white' : 'black',
                    backgroundColor: isActiveBtns.includes(item.point) ? '#3B82F6' : 'white'
                  }"
                >
                  <component :is="item.isAlarm ? iconComList['point_warning'] : iconComList[item?.icon]" class="content-icon color-total" />
                  <div class="point_name">{{ item?.iName }}:</div>
                  <div class="pop_value">{{ item?.iValue }}{{ item?.unit }}</div>
                </div>
              </template>
            </px-popover>
          </div>
        </div> -->
      </div>
      <div v-show="showCharts" class="con-chart-tabs">
        <px-tabs v-model="tabsName" type="card" @tab-change="changeTabsFn">
          <px-tab-pane label="趋势" name="one" />
          <!-- <px-tab-pane label="热力" name="many" /> -->
        </px-tabs>
        <div class="chart_con">
          <div v-if="tabsName === 'one'" v-loading="lineChartLoading" class="chart_item">
            <lineChart ref="areaChartRef" :key="midKey + 10" :border="false" :options="linesOptions" :width="600" :height="458" />
          </div>
          <div v-if="tabsName === 'many'" class="chart_item">
            <lineChart ref="heatMapRef" :key="midKey" :border="false" :options="heatMapOptions" :width="600" :height="458" />
            <!-- <div ref="heatMapRef" style="min-width: 600px; height: 480px; border: 1px solid #dcdcdc" /> -->
          </div>
        </div>
      </div>
      <div class="con-contro">
        <px-image style="width: 30px; height: 30px; cursor: pointer" :src="btnImgUrl" @click="showCharts = !showCharts" />
      </div>
    </div>
    <!-- <div class="page-con">
      <div class="tabs">
        <CustomTabs :tabList="tabsOption" :activeName="activeName" @tabSelect="tabSelectHandler" />
      </div>
      <div ref="switchTabsContentRef">
        <px-scrollbar class="con_bar">
          <transition name="fab-tabs-fade" mode="out-in">
            <component
              :is="activeCom"
              :activeIndex="activeIndex"
              :allCheckoutbox="allCheckoutbox"
              :checkAreaList="checkAreaList"
              :activeName="activeName"
            />
          </transition>
        </px-scrollbar>
      </div>
    </div> -->
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "MACHINE_OPERATION_VISUAL"
});
import CustomTabs from "@/components/Tabs/index.vue";
import { ref, markRaw, computed, onMounted, onUnmounted, nextTick, toRefs, reactive, getCurrentInstance } from "vue";
import barTitle from "@/views/machine/components/barTitle/index.vue";
import timeItem from "../components/timeItem/index.vue";
import weatherTop from "../components/weatherTop/index.vue";
import weatherItem from "../components/weatherItem/index.vue";
import WeatherList from "@/views/all/bench/task/weather/components/WeatherList/index.vue";
import alarmTable from "../components/alarmTable/index.vue";
import allPoints from "../components/allPoints/index.vue";
import { type OptionsType } from "@/components/ReSegmented";
import { useUpdateDomHeight, useCancelUpdateDomHeight } from "@/hooks/useCommon";
import type { UtilsEChartsOption } from "@pureadmin/utils";
import lineChart from "../components/lineChart/index.vue";
import { spcquerySpcAnalysis } from "@/api/spc";
import { useRouter } from "vue-router";
import { debounce } from "@pureadmin/utils";
import { PxMessage } from "px-ui";
import dayjs from "dayjs";
import {
  queryWeatherData,
  getFabZone,
  getReadersInZone,
  getPointNewValue,
  getReadersInZoneByType,
  getPointsCurve,
  addRemake,
  remakeHistory,
  queryChildByTypeCodeAndItemValue,
  queryAreaWornings
} from "@/api/machineClass";
import { querySpecValues, getReadersInZoneByTypes, getAreaWarnings, getMaxMin, getPID } from "@/api/machineApi";
import MinimapPanel from "@/views/machine/operation/environmentTestManage/fabHeatMap/components/MinimapPanel.vue";
import allPointData from "@/views/machine/operation/environmentTestManage/visualManage/components/allPointData.json";
import allPointData2 from "@/views/machine/operation/environmentTestManage/visualManage/components/allPointData2.json";
import { queryWeatherNow } from "@/api/bench";

import point_dcc from "@/assets/svg/machine/point_dcc.svg?component";
import point_env from "@/assets/svg/machine/point_env.svg?component";
import point_mau from "@/assets/svg/machine/point_mau.svg?component";
import point_warning from "@/assets/svg/machine/point_warning.svg?component";

const iconComList = {
  point_dcc: markRaw(point_dcc),
  point_env: markRaw(point_env),
  point_mau: markRaw(point_mau),
  point_warning: markRaw(point_warning)
};

const facCode = ref(localStorage.getItem("facCode")); // 一期：facCode: "FAC_83abf9",

const JSON_DATA = computed(() => {
  if (facCode.value === "FAC_83abf9") {
    return allPointData;
  } else {
    return allPointData2;
  }
});

onMounted(() => {
  nextTick(() => {});
  console.log(JSON_DATA.value);
});

const { proxy }: any = getCurrentInstance();

const queryBtnLoading = ref(false);

const areaChartRef = ref(null);

const lineChartLoading = ref(false);

const minimapImageSize = ref({
  width: 1850,
  height: "auto"
});

const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)];

const state = reactive<any>({
  weatherForm: {
    num: 1,
    type: "hour"
  },
  Detail: {
    testCompany: "12 minutes"
  },
  spcJobList: [],
  weatherSpcJobList: [],
  areaData: [],
  environData: [],
  checkAreaList: [],
  pointsList: [],
  particleData: [],
  amcData: [],
  eqpData: [],
  dateRangeSpc: [],
  targetList: [],
  targetList2: [],
  targetList3: [],
  targetList4: [1, 2],
  dataDetailTable: [],
  dateRangeSpcDetail: [],
  heatMapOptions: {},
  upDownData: [],
  popoverData: {},
  linesOptions: {},
  pointData: [],
  allAlarmList: [],
  isActiveBtns: [],
  weatherOptions: {},
  querySpcDetailParams: {},
  currentMapImage:
    facCode.value === "FAC_83abf9"
      ? `${proxy.useGetStaticUrl(`/ifp-web-static/image/machine/clearRoom/WST.png`)}`
      : `${proxy.useGetStaticUrl(`/ifp-web-static/image/machine/clearRoom2/洁净室.png`)}`,
  currentBackgroundImage:
    facCode.value === "FAC_83abf9"
      ? `${proxy.useGetStaticUrl("/ifp-web-static/image/machine/clearRoom/WST-2.5d.png")}`
      : `${proxy.useGetStaticUrl(`/ifp-web-static/image/machine/clearRoom2/WST-2.5d.png`)}`,
  weatherData: {}
});

const {
  isActiveBtns,
  pointData,
  allAlarmList,
  environData,
  particleData,
  amcData,
  popoverData,
  eqpData,
  weatherForm,
  pointsList,
  areaData,
  checkAreaList,
  weatherData,
  dataDetailTable,
  heatMapOptions,
  linesOptions,
  targetList,
  targetList2,
  targetList3,
  targetList4,
  Detail,
  dateRangeSpc,
  dateRangeSpcDetail,
  spcJobList,
  weatherSpcJobList,
  querySpcDetailParams,
  weatherOptions,
  currentMapImage,
  currentBackgroundImage,
  upDownData
} = toRefs(state);

const showCharts = ref(false);

const isClick = ref(true);

const currentArea = ref("");

const searchId = ref("");

const midKey = ref(Date.now());

const btnImgUrl = computed(() => {
  if (showCharts.value) {
    return new URL(`../../../../../assets/images/machine/right.png`, import.meta.url).href;
  } else {
    return new URL(`../../../../../assets/images/machine/left.png`, import.meta.url).href;
  }
});

const mauSelectValue = computed(() => {
  return eqpData.value.filter(e => ["MCTSCI05AV01", "MCTSCI05AV02", "MCTSCI05AV03"].includes(e.itemValue)).map(i => i.type);
});

const mauSelectName = computed(() => {
  return eqpData.value
    .filter(e => ["MCTSCI05AV01", "MCTSCI05AV02", "MCTSCI05AV03"].includes(e.itemValue))
    .map(i => i.itemName)
    .join("&");
});

const dccSelectValue = computed(() => {
  return eqpData.value.filter(e => ["MCTSCI05AV04", "MCTSCI05AV05"].includes(e.itemValue)).map(i => i.type);
});

const dccSelectName = computed(() => {
  return eqpData.value
    .filter(e => ["MCTSCI05AV04", "MCTSCI05AV05"].includes(e.itemValue))
    .map(i => i.itemName)
    .join("&");
});

const selectedCheckbox = computed(() => {
  if (targetList4.value.includes(1) && targetList4.value.includes(2)) {
    return dccSelectValue.value.concat(mauSelectValue.value);
  } else if (targetList4.value.includes(1) && !targetList4.value.includes(2)) {
    return mauSelectValue.value;
  } else if (!targetList4.value.includes(1) && targetList4.value.includes(2)) {
    return dccSelectValue.value;
  } else {
    return [];
  }
});

const allCheckoutbox = computed(() => {
  return [...targetList.value.concat(selectedCheckbox.value, targetList2.value, targetList3.value)];
});

const dateTime = ref();
const getWeatherNow = async () => {
  dateTime.value = dayjs().format("YYYY-MM-DD");
  const data = await queryWeatherNow(dateTime.value);
  weatherData.value = data?.now || {};
};

const getUnit = (value, list) => {
  const obj = list.find(e => e.itemValue === value);
  return JSON.parse(obj?.itemDesc.replace(/[\r|\n|\t]/g, ""))?.unit || "";
};

const getPoint = (name, list) => {
  if (!list.length) return "";
  return list.find(e => e.specName === name)?.specId;
};

// 获取上下限
const getUpDown = id => {
  if (!upDownData.value.length) return false;
  return upDownData.value.find(e => e.specId === id)?.formulaDesc.split(",");
};

// 获取值
const getValue = (id, type) => {
  if (!upDownData.value.length) return false;
  return upDownData.value.find(e => e.specId === id)?.[type];
};

const defaultHeight = ref<number>(700);

const activeIndex = ref(0);

const router = useRouter();

const tabsOption = ref<Array<OptionsType>>([
  {
    name: "报警明细",
    label: "报警明细",
    com: markRaw(alarmTable)
  },
  {
    name: "全部点位",
    label: "全部点位",
    com: markRaw(allPoints)
  }
]);

const loading = ref(false);

const tabsName = ref("one");

const visibleY2 = ref(false);

const showSpcDetail = ref(false);

const activeName = ref("报警明细");

const typeList = [
  {
    value: "hour",
    label: "小时"
  },
  {
    value: "day",
    label: "日"
  }
];

const testCompanyList = ref<any>([
  {
    value: "12 minutes",
    key: 240,
    label: "近4小时"
  },
  {
    value: "3 minutes",
    key: 60,
    label: "近1小时"
  },
  {
    value: "60 seconds",
    key: 30,
    label: "近30分钟"
  },
  {
    value: "20 seconds",
    key: 10,
    label: "近10分钟"
  },
  {
    value: "1 hours",
    key: 1440,
    label: "近1天"
  },
  {
    value: "7 hours",
    key: 10080,
    label: "近7天"
  },
  {
    value: "1 days",
    key: 43200,
    label: "近30天"
  }
]);

const switchTabsContentRef = ref(null);

const activeCom = computed(() => tabsOption.value.find(item => item.name === activeName.value).com);
const switchTabsChangeHandler = async () => await useUpdateDomHeight(defaultHeight, switchTabsContentRef, null, defaultHeight.value);

const changeTabsFn = async (val: any) => {
  // const lineChartDom = await areaChartRef.value.getEcharts();
  // lineChartDom.resize();
};

const handleQuerySpc = (val: string) => {
  const num: number = testCompanyList.value.filter(item => item.value === val)[0].key;
  if (val) {
    dateRangeSpc.value = initDate(num);
  }
};

const tabsClick = (item, index) => {
  activeName.value = "报警明细";
  if (activeIndex.value === index) {
    return;
  }
  // 清空点位打点和图表
  pointData.value = [];
  heatMapOptions.value = {};
  linesOptions.value = {};
  showCharts.value = false;
  queryBtnLoading.value = false;
  checkAreaList.value = [item.name];
  isActiveBtns.value = [];
  console.log(
    areaData.value.find(el => el.name === item.name),
    "777777777777777"
  );
  if (areaData.value.find(el => el.name === item.name)) {
    if (facCode.value === "FAC_83abf9") {
      currentMapImage.value = `${proxy.useGetStaticUrl(`/ifp-web-static/image/machine/clearRoom/${item.name}.png`)}`;
      currentBackgroundImage.value = `${proxy.useGetStaticUrl(`/ifp-web-static/image/machine/clearRoom/${item.name}-2.5d.png`)}`;
    } else {
      currentMapImage.value = `${proxy.useGetStaticUrl(`/ifp-web-static/image/machine/clearRoom2/${item.name}.png`)}`;
      currentBackgroundImage.value = `${proxy.useGetStaticUrl(`/ifp-web-static/image/machine/clearRoom2/${item.name}-2.5d.png`)}`;
    }
  } else {
    if (facCode.value === "FAC_83abf9") {
      currentMapImage.value = `${proxy.useGetStaticUrl(`/ifp-web-static/image/machine/clearRoom/洁净室.png`)}`;
      currentBackgroundImage.value = `${proxy.useGetStaticUrl(`/ifp-web-static/image/machine/clearRoom/WST-2.5d.png`)}`;
    } else {
      currentMapImage.value = `${proxy.useGetStaticUrl(`/ifp-web-static/image/machine/clearRoom2/洁净室.png`)}`;
      currentBackgroundImage.value = `${proxy.useGetStaticUrl(`/ifp-web-static/image/machine/clearRoom2/WST-2.5d.png`)}`;
    }
  }
  // currentBackgroundImage.value = areaData.value.find(el => el.name === item.name)
  //   ? `${proxy.useGetStaticUrl(`/ifp-web-static/image/machine/clearRoom/${item.name}-2.5d.png`)}`
  //   : `${proxy.useGetStaticUrl(`/ifp-web-static/image/machine/clearRoom/洁净室-2.5d.png`)}`;
  // currentMapImage.value = areaData.value.find(el => el.name === item.name)
  //   ? `${proxy.useGetStaticUrl(`/ifp-web-static/image/machine/clearRoom/${item.name}.png`)}`
  //   : `${proxy.useGetStaticUrl(`/ifp-web-static/image/machine/clearRoom/洁净室.png`)}`;
  activeIndex.value = index;
  // 当前激活的区域
  currentArea.value = areaData.value[activeIndex.value].name;
  searchId.value = item.code;
  // queryTable();
  // queryPointsList();
  // targetList.value = [];
  // targetList2.value = [];
  // targetList3.value = [];
  // targetList4.value = [];
  handleQuery();
};

const getWeatherData = async () => {
  const param = {
    diffHours: weatherForm.value.num || 1
  };
  const data = await queryWeatherData(param);
  weatherData.value = data;
};

// 获取区域列表
const queryAreaList = async (id: string) => {
  const data: any = await getFabZone();
  const codeList = data && data.map(e => e.code);
  const roomObj: any = await getAreaWarnings(codeList.filter(e => e.includes("ROOM")));
  const areaObj: any = await getAreaWarnings(codeList.filter(e => !e.includes("ROOM")));
  const obj = Object.assign(roomObj, areaObj);
  const arr = data.map((item: any) => {
    Object.keys(obj).forEach(el => {
      if (item.code === el) {
        item.worningNum = obj[el];
      }
    });
    return item;
  });
  areaData.value = arr;
  checkAreaList.value = [areaData.value[activeIndex.value].name];
  // 当前激活的区域
  currentArea.value = areaData.value[activeIndex.value].name;
  if (areaData.value.find(el => el.name === currentArea.value)) {
    if (facCode.value === "FAC_83abf9") {
      currentMapImage.value = `${proxy.useGetStaticUrl(`/ifp-web-static/image/machine/clearRoom/${currentArea.value}.png`)}`;
      currentBackgroundImage.value = `${proxy.useGetStaticUrl(`/ifp-web-static/image/machine/clearRoom/${currentArea.value}-2.5d.png`)}`;
    } else {
      currentMapImage.value = `${proxy.useGetStaticUrl(`/ifp-web-static/image/machine/clearRoom2/${currentArea.value}.png`)}`;
      currentBackgroundImage.value = `${proxy.useGetStaticUrl(`/ifp-web-static/image/machine/clearRoom2/${currentArea.value}-2.5d.png`)}`;
    }
  } else {
    if (facCode.value === "FAC_83abf9") {
      currentMapImage.value = `${proxy.useGetStaticUrl(`/ifp-web-static/image/machine/clearRoom/洁净室.png`)}`;
      currentBackgroundImage.value = `${proxy.useGetStaticUrl(`/ifp-web-static/image/machine/clearRoom/WST-2.5d.png`)}`;
    } else {
      currentMapImage.value = `${proxy.useGetStaticUrl(`/ifp-web-static/image/machine/clearRoom2/洁净室.png`)}`;
      currentBackgroundImage.value = `${proxy.useGetStaticUrl(`/ifp-web-static/image/machine/clearRoom2/WST-2.5d.png`)}`;
    }
  }
  searchId.value = areaData.value[activeIndex.value].code;
};

// 日期转化
const initDate = (val: number) => {
  const now = new Date();
  const utcTime = now.toISOString();
  const beijingTime = new Date(utcTime).getTime() + 8 * 60 * 60 * 1000;
  const start = beijingTime - val * 60 * 1000;
  const startTime = new Date(start).toISOString().slice(0, 19).replace("T", " ");
  const endTime = new Date(beijingTime).toISOString().slice(0, 19).replace("T", " ");
  return [startTime, endTime];
};

const initSpcDate = () => {
  const date = new Date();
  let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString();
  let da = date.getDate() < 10 ? "0" + date.getDate().toString() : date.getDate().toString();
  let hour = date.getHours() < 10 ? "0" + date.getHours().toString() : date.getHours().toString();
  let minites = date.getMinutes() < 10 ? "0" + date.getMinutes().toString() : date.getMinutes().toString();
  let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds().toString() : date.getSeconds().toString();
  let lastda = date.getDate() < 10 ? "0" + (date.getDate() + 1).toString() : (date.getDate() + 1).toString();
  let year = date.getFullYear();
  let lastYear = date.getFullYear() - 1;
  return [`${year}-${month}-${da}`, `${year}-${month}-${da}`]; // 近一年时间范围
  // return [`${year}-${month}-${lastda} 00:00:00`, `${year}-${month}-${da} ${hour}:${minites}:${seconds}`]; // 近一年时间范围
};

const viewSpcDetail = () => {
  router.push({
    path: "/all/bench/task/weather",
    query: {
      page: "/machine/operation/environmentTestManage/visualManage"
    }
  });
};

const turnBack = () => {
  showSpcDetail.value = false;
};

const mins = computed(() => {
  return testCompanyList.value.filter(item => item.value === Detail.value.testCompany)[0].key;
});

const getParams = computed(() => {
  const obj = {
    startTime: dateRangeSpc.value[0],
    endTime: dateRangeSpc.value[1],
    zones: [],
    types: [],
    factory: {
      id: 1,
      parentCode: "",
      code: "",
      name: "",
      type: "",
      path: "",
      // facCode: "FAC_83abf9",
      principalId: 1,
      principalName: "",
      className: "MACHINE",
      children: [
        {
          id: 1,
          parentCode: "",
          code: "",
          name: "",
          type: "",
          path: "",
          // facCode: "",
          principalId: 1,
          principalName: "",
          className: ""
        }
      ]
    },
    requestId: ""
  };
  // if (tabsName.value === "one") {
  //   obj.types = [...targetList.value];
  //   obj.zones = [...checkAreaList.value];
  //   return obj;
  // } else {
  //   obj.types = [...targetList.value];
  //   obj.zones = [...checkAreaList.value];
  //   return obj;
  // }
  obj.types = [...targetList.value.concat(selectedCheckbox.value, targetList2.value, targetList3.value)];
  obj.zones = [...checkAreaList.value];
  return obj;
});

// 循环获取点位列表，再循环点位列表获取热力图数据
// const getPointsList = async (param: any, arr) => {
//   const pointObj: any = await getReadersInZoneByTypes(param);
//   if (Object.keys(pointObj) && Object.keys(pointObj).length > 0) {
//     Object.keys(pointObj).forEach(el => {
//       arr.push({
//         iName: el,
//         point: pointObj[el].split("=")[0],
//         top: `${parseInt(pointObj[el].split("=")[1].slice(1, -1).split(",")[0])}px`,
//         left: `${parseInt(pointObj[el].split("=")[1].slice(1, -1).split(",")[1])}px`
//       });
//     });
//   }
//   JSON_DATA.value = arr;
//   console.log(JSON_DATA.value, "JSON_DATA.value");
// };

// 获取区域列表
// const queryAreaList = async (id: string) => {
//   const data: any = await getFabZone({ id });
//   areaData.value = data;
//   searchId.value = areaData.value[props.activeIndex].code; // 默认查询选中的区域
//   queryTable();
// };

// const queryAlarmList = async () => {
//   // 通过厂区字典查询区域
//   const codes: any = await queryChildByTypeCodeAndItemValue({
//     value: "CR_ALL_CODES",
//     typeCode: "MCTS"
//   });
//   const id = JSON.parse(codes.filter(item => item.itemValue === "CR_POSITION_CODE")[0].itemDesc)[0].facCode; // 暂时写死一期厂区
//   await queryAreaList(id);
// };

const isShowAlarm = val => {
  // console.log(val, allAlarmList.value, "12321313");
  for (let i = 0; i < allAlarmList.value.length; i++) {
    if (allAlarmList.value[i].point.includes(val) && allAlarmList.value[i].point !== val) {
      return true;
    }
  }
  return false;
};

// 根据点位查询点位最新值
const getPointListNewValue = async (arr: any) => {
  // const isAlarmUrl = new URL(`../../../../../assets/svg/machine/warning.png`, import.meta.url).href;
  // const notAlarmUrl = new URL(`../../../../../assets/svg/machine/normal.png`, import.meta.url).href;
  if (arr.length || JSON_DATA.value[currentArea.value].length) {
    // const res: any = await querySpecValues(arr && arr.length ? arr : JSON_DATA.value[currentArea.value].map(e => e.point));
    const params = {
      // areaId: id, // id 暂时写死联调
      // roomId: "ROOM_b20032", // id 暂时写死联调
      pageNum: 1,
      pageSize: 999
    };
    params[`${searchId.value.indexOf("ROOM") === -1 ? "areaId" : "roomId"}`] =
      searchId.value.indexOf("ROOM") === -1 ? [searchId.value] : searchId.value;
    const param = proxy.addDateRange(params, dateRangeSpc.value, "startTime", "endTime");
    const data: any = await queryAreaWornings(param);
    allAlarmList.value = data.data && data.data.length ? data.data : [];
    const pointArr = JSON_DATA.value[currentArea.value].map(e => e.point);
    const maxminData: any = (await getMaxMin({ tagCodes: pointArr })) || [];
    // 根据返回的点位最新值数据反查对应指标
    pointData.value = JSON_DATA.value[currentArea.value].map(e => {
      return {
        ...e,
        min: maxminData.find(item => item.tagCode === e.point) ? maxminData.find(item => item.tagCode === e.point).tableValueMin : "",
        max: maxminData.find(item => item.tagCode === e.point) ? maxminData.find(item => item.tagCode === e.point).tableValueMax : "",
        yxiasMin: getUpDown(e.point) ? getUpDown(e.point)[0] : null,
        yxiasMax: getUpDown(e.point) ? getUpDown(e.point)[1] : null,
        iValue: getValue(e.point, "currentValue") ? getValue(e.point, "currentValue") : "-",
        unit: getValue(e.point, "unit") ? getValue(e.point, "unit") : "-",
        specName: getValue(e.point, "specName") ? getValue(e.point, "specName") : "-",
        isAlarm: isShowAlarm(e.point) ? true : e.isAlarm
      };
    });
    console.log(pointData.value, "pointData.value");
    queryBtnLoading.value = false;
  } else {
    return;
  }
};

// 循环调用接口获取点位列表
const getHotPointes = async () => {
  if (!allCheckoutbox.value.length) {
    PxMessage.warning("请选择指标");
    return;
  }
  let arr = [];
  // console.log(getParams.value, "getParams.value,区域/指标");
  // for (let i = 0; i < getParams.value.zones.length; i++) {
  //   for (let j = 0; j < getParams.value.types.length; j++) {
  //     const str1 = getParams.value.zones[i];
  //     const str2 = getParams.value.types[j];
  //     const obj = {
  //       ...getParams.value
  //     };
  //     obj.zones = [str1];
  //     obj.types = [str2];
  //     await getPointsList(obj, arr);
  //   }
  // }

  const obj = {
    ...getParams.value
  };
  // await getPointsList(obj, arr);
};

// 热力图
const queryHeatMap = async (param, list, obj, row) => {
  lineChartLoading.value = true;
  // const param = {
  //   panelCode: "cr_heatmap",
  //   criterial: {
  //     timespan: Detail.value.testCompany,
  //     startTime: dateRangeSpc.value[0],
  //     endTime: dateRangeSpc.value[1],
  //     points: ["AMC_F_LITHO"]
  //   }
  // };
  const res: any = await getPointNewValue(param);
  if (res.rows.length) {
    list.push({
      unit: pointData.value.find(item => item.point === res.rows[0].point) ? pointData.value.find(item => item.point === res.rows[0].point).unit : "",
      min: pointData.value.find(item => item.point === res.rows[0].point) ? pointData.value.find(item => item.point === res.rows[0].point).min : "",
      max: pointData.value.find(item => item.point === res.rows[0].point) ? pointData.value.find(item => item.point === res.rows[0].point).max : "",
      iName: pointData.value.find(item => item.point === res.rows[0].point).iName,
      specName: pointData.value.find(item => item.point === res.rows[0].point).specName,
      yxiasMin: pointData.value.find(item => item.point === res.rows[0].point)
        ? pointData.value.find(item => item.point === res.rows[0].point).yxiasMin
        : "",
      yxiasMax: pointData.value.find(item => item.point === res.rows[0].point)
        ? pointData.value.find(item => item.point === res.rows[0].point).yxiasMax
        : "",
      ...res
    });
  } else {
    list = [];
  }
  console.log(list, "全部曲线");
  const hours = list && list.length ? list[0].rows.map(item => item.timespan) : [];
  // console.log(hours, "横坐标");
  // const seriesHeatMap = list.map((item, index) => {
  //   return {
  //     name: checkAreaList.value[index] || (item.rows && item.rows[0].point.split("_")[item.rows[0].point.split("_").length - 1]),
  //     type: "heatmap",
  //     data: item.rows
  //       .map((el, ind) => {
  //         return [index, ind, el.last_value];
  //       })
  //       .map(function (e) {
  //         return [e[1], e[0], e[2] || "-"];
  //       }),
  //     label: {
  //       show: true
  //     },
  //     itemStyle: {
  //       normal: {
  //         // width: 30,// 设置格子宽度
  //         height: 30 // 设置格子高度
  //       }
  //     },
  //     emphasis: {
  //       itemStyle: {
  //         shadowBlur: 10,
  //         shadowColor: "rgba(0, 0, 0, 0.5)"
  //       }
  //     }
  //   };
  // });
  const seriesLine = list.map((item, index) => {
    return {
      name: item.specName, // checkAreaList.value[index] ||
      type: "line",
      yAxisIndex: index,
      emphasis: {
        focus: "series",
        blurScope: "coordinateSystem"
      },
      data: item.rows.map(e => Number(e.last_value))
    };
  });
  // seriesLine.[0].markLine = {
  //   symbol: "none",
  //   data: [
  //     {
  //       name: "LWL值",
  //       yAxis: Number(response[0].lwlValue != null ? response[0].lwlValue : 0),
  //       lineStyle: {
  //         color: "#ffca45",
  //         wideh: "1",
  //         type: "solide"
  //       },
  //       label: {
  //         position: "insideEndBottom",
  //         formatter: `内控要求>${response[0].lwlValue != null ? response[0].lwlValue : ''}${response[0].pointUnit || ''}`,
  //         color: "#ffca45"
  //       }
  //     },
  //     {
  //       name: "UWL值",
  //       yAxis: Number(response[0].uwlValue != null ? response[0].uwlValue : 0),
  //       lineStyle: {
  //         color: "#ffca45",
  //         wideh: "1",
  //         type: "solide"
  //       },
  //       label: {
  //         position: "insideEndTop",
  //         formatter: `内控要求<${response[0].uwlValue != null ? response[0].uwlValue : ''}${response[0].pointUnit || ''}`,
  //         color: "#ffca45"
  //       }
  //     }
  //   ]
  // };
  const yAxisData = list.map((item, index) => {
    return {
      type: "value",
      // scale: true,
      name: `${item.specName}\n(量程:${item.min != null ? item.min : ""}~${item.max != null ? item.max : ""})\n${item.unit}`,
      alignTicks: true,
      offset: (0 + index) * 70,
      axisLine: {
        show: true
      },
      max: item.yxiasMax,
      min: item.yxiasMin,
      axisLabel: {
        formatter: function (value) {
          return Math.ceil(Number(value.toFixed(2)));
        }
      },
      // nameLocation: "left",
      // nameRotate: -90,
      nameTextStyle: {
        fontSize: 10
      }
    };
  });
  console.log(yAxisData, "yAxisDatayAxisDatayAxisData");
  // prettier-ignore
  // const days = areaData.value.map((item: any) => item.name);
  // const yData = checkAreaList.value;
  // const yData = seriesHeatMap.map(item => item.name);
  // console.log(seriesHeatMap, yData, hours, "热力图数据-y轴-X轴");
  // console.log(seriesLine, yAxisData, hours, "折线图数据-y轴-X轴");
  // prettier-ignore
  // const data = [[0, 0, 5], [0, 1, 1], [0, 2, 0], [0, 3, 0], [0, 4, 0], [0, 5, 0], [0, 6, 0], [0, 7, 0], [0, 8, 0], [0, 9, 0], [0, 10, 0], [0, 11, 2], [0, 12, 4], [0, 13, 1], [0, 14, 1], [0, 15, 3], [0, 16, 4], [0, 17, 6], [0, 18, 4], [0, 19, 4], [0, 20, 3], [0, 21, 3], [0, 22, 2], [0, 23, 5], [0, 24, 7], [0, 25, 0], [0, 26, 0], [0, 27, 0], [0, 28, 0], [0, 29, 0], [0, 30, 0], [0, 31, 0]]
  //   .map(function (item) {
  //     return [item[1], item[0], item[2] || '-'];
  //   });
  // console.log(data, "热力图data");
  // const options: UtilsEChartsOption = {
  //   title: {
  //     text: "Temperature Distribution Across FAB Areas Over Time",
  //     textStyle: {
  //       fontSize: 16
  //     },
  //     // subtext: "曲线标题",
  //     left: "left",
  //     top: "top",
  //     padding: [10, 0, 0, 20]
  //   },
  //   tooltip: {
  //     position: "top"
  //   },
  //   grid: {
  //     height: "68%",
  //     left: "8%",
  //     top: "10%",
  //     right: "24px"
  //   },
  //   xAxis: {
  //     type: "category",
  //     data: hours || [],
  //     splitArea: {
  //       show: true
  //     }
  //   },
  //   yAxis: {
  //     type: "category",
  //     data: yData || [],
  //     splitArea: {
  //       show: true
  //     }
  //   },
  //   visualMap: {
  //     // pieces: [
  //     //   { min: 0, max: 5, color: "blue" },
  //     //   { min: 6, max: 10, color: "red" }
  //     // ],
  //     min: 0,
  //     max: 15,
  //     calculable: true,
  //     orient: "horizontal",
  //     left: "center",
  //     bottom: "2%"
  //   },
  //   series: seriesHeatMap || []
  // };
  const lineOptions: UtilsEChartsOption = {
    title: {
      text: "Temperature Trends Across FAB Areas Over Time",
      textStyle: {
        fontSize: 16
      },
      // subtext: "曲线标题",
      left: "left",
      top: "top",
      padding: [10, 0, 0, 20]
    },
    tooltip: {
      trigger: "axis",
      confine: true
    },
    legend: {
      type: "scroll",
      // pager: {
      //   orient: "vertical",
      //   pageButtonItemGap: 5
      // },
      // data: props.areaList.map((item: any) => item.name),
      data: seriesLine.map(item => item.name) || [],
      orient: "horizontal",
      bottom: "0"
    },
    grid: {
      left: "5%",
      top: "20%",
      right: `${yAxisData.length * 50}`,
      bottom: "24PX",
      containLabel: true
    },
    xAxis: {
      // type: "category",
      data: hours || []
    },
    yAxis: yAxisData || [],
    series: seriesLine || []
  };
  // heatMapOptions.value = options;
  // const lineChartDom = await areaChartRef.value.getEcharts();
  // console.log(areaChartRef.value, lineChartDom, "9999999");
  // lineChartDom.setOptions(lineOptions);
  linesOptions.value = lineOptions;
  midKey.value = Date.now();
};

// 查询
const handleQuery = async () => {
  // 清空图表
  pointData.value = [];
  heatMapOptions.value = {};
  linesOptions.value = {};
  // showCharts.value = false;
  // queryBtnLoading.value = false;
  isActiveBtns.value = [];
  // queryBtnLoading.value = true;
  // await getHotPointes();
  await getPIDdata();
  if (JSON_DATA.value[currentArea.value] && JSON_DATA.value[currentArea.value].length) {
    getPointListNewValue(JSON_DATA.value[currentArea.value].map(e => e.point));
  }
};

/** 重置按钮操作 */
function resetQuery() {
  const startTime = proxy.parseTime(new Date().getTime() - 240 * 60 * 1000, "{y}-{m}-{d} {h}:{i}:{s}");
  const endTime = proxy.parseTime(new Date().getTime(), "{y}-{m}-{d} {h}:{i}:{s}");
  dateRangeSpc.value = [startTime, endTime];
  Detail.value.testCompany = "12 minutes";
  handleQuery();
}

// 查询报警明细
const querySpc = async () => {
  // const cwData = await queryChildByTypeCodeAndItemValue({
  //   value: "CWConfig",
  //   typeCode: "MCTS"
  // });
  // spcDataList.value = cwData ? cwData : [];
  // const jobIDs = [];
  // spcDataList.value.forEach((item: any) => {
  //   jobIDs.push(JSON.parse(item.itemDesc).spc_job);
  // });
  const params = {
    jobIdList: [...spcJobList.value],
    timePeriod: "hour",
    startTime: dateRangeSpcDetail.value[0] + " 00:00:00",
    endTime: dateRangeSpcDetail.value[1] + " 23:59:59"
  };
  const res: any = await spcquerySpcAnalysis(params);
  // 需要展示的SPC 可替换下方jobIdS
  // const showSpcIds = [
  //   "weather.outdoor.temp.dry_1",
  //   "SPC_QA_CWConfig11",
  //   "SPC_QA_CWConfig12",
  //   "SPC_QA_CWConfig1",
  //   "SPC_QA_CWConfig2",
  //   "SPC_QA_CWConfig3",
  //   "SPC_QA_CWConfig4",
  //   "SPC_QA_CWConfig7",
  //   "SPC_QA_CWConfig8"
  // ];
  // 过滤
  // const arr = res.filter((item: any) => jobIDs.indexOf(item.jobId) !== -1 && item.pointValues && item.pointValues.length > 0); // 过滤出有数据的
  const arr = res.filter((item: any) => spcJobList.value.indexOf(item.jobId) !== -1); // 过滤出有数据的
  const spcList = arr.map((item: any) => {
    item.startTime = dateRangeSpcDetail.value[0];
    item.endTime = dateRangeSpcDetail.value[1];
    item.pointValues = item.pointValues ? item.pointValues : []; // null时判断，有数据可放开
    return {
      ...item
    };
  });
  dataDetailTable.value = spcList;
  const obj = spcList[0];
  // weatherOptions.value = obj;

  const yAxis =
    spcList &&
    spcList.map((item, index) => {
      return {
        type: "value",
        name: obj.indicatorName,
        nameLocation: "middle", //居中
        offset: (0 + index) * 50,
        nameGap: 70, //轴线距离
        nameRotate: 90, //字体选择角度
        axisLine: {
          show: true,
          lineStyle: {
            type: "solid"
          }
        }
      };
    });
  const series =
    spcList &&
    spcList.map((obj, ind) => {
      return {
        // data: [400, 400, 400, 400, 400, 400],
        data: obj && obj.pointValues.length > 0 ? obj.pointValues.map(item => item.value) : [],
        type: "line",
        name: obj.indicatorName,
        yAxisIndex: ind,
        // areaStyle: {
        //   opacity: 0.15
        // },
        symbol: "none",
        markLine: {
          symbol: "none",
          data: [
            {
              name: "USL值",
              yAxis: Number(obj.uslValue),
              lineStyle: {
                color: "#A600FF",
                wideh: "1",
                type: "solide"
              },
              label: {
                position: "insideEndTop",
                formatter: `USL值${obj.uslValue}`,
                color: "#A600FF",
                fontWeight: 600
              }
            },
            {
              name: "UCL值",
              yAxis: Number(obj.uclValue),
              lineStyle: {
                color: "#FF0000",
                wideh: "1",
                type: "dashed"
              },
              label: {
                position: "insideEndTop",
                formatter: `UCL值${obj.uclValue}`,
                color: "#FF0000",
                fontWeight: 600
              }
            },
            {
              name: "UWL值",
              yAxis: Number(obj.uwlValue),
              lineStyle: {
                color: "#FF9900",
                wideh: "1",
                type: "dashed"
              },
              label: {
                position: "insideEndTop",
                formatter: `UWL值${obj.uwlValue}`,
                color: "#FF9900",
                fontWeight: 600
              }
            },
            {
              name: "Target值",
              yAxis: Number(obj.targetValue),
              lineStyle: {
                color: "#00E272",
                wideh: "1",
                type: "solide"
              },
              label: {
                position: "insideEndTop",
                formatter: `Target值${obj.targetValue}`,
                color: "#00E272",
                fontWeight: 600
              }
            },
            {
              name: "LWL值",
              yAxis: Number(obj.lwlValue),
              lineStyle: {
                color: "#FF9900",
                wideh: "1",
                type: "dashed"
              },
              label: {
                position: "insideEndTop",
                formatter: `LWL值${obj.lwlValue}`,
                color: "#FF9900",
                fontWeight: 600
              }
            },
            {
              name: "LCL值",
              yAxis: Number(obj.lclValue),
              lineStyle: {
                color: "#FF0000",
                wideh: "1",
                type: "dashed"
              },
              label: {
                position: "insideEndTop",
                formatter: `LCL值${obj.lclValue}`,
                color: "#FF0000",
                fontWeight: 600
              }
            },
            {
              name: "LSL值",
              yAxis: Number(obj.lslValue),
              lineStyle: {
                color: "#A600FF",
                wideh: "1",
                type: "solide"
              },
              label: {
                position: "insideEndTop",
                formatter: `LSL值${obj.lslValue}`,
                color: "#A600FF",
                fontWeight: 600
              }
            }
          ]
        }
      };
    });
  const legendData = spcList && spcList.map(item => item.indicatorName);
  const option = {
    color: "#ccc",
    grid: {
      left: "60px",
      top: "40px",
      right: "100px",
      bottom: "5%",
      containLabel: true
    },
    legend: {
      type: "scroll",
      // pager: {
      //   orient: "vertical",
      //   pageButtonItemGap: 5
      // },
      data: legendData,
      orient: "horizontal",
      bottom: "0"
    },
    tooltip: {
      trigger: "axis",
      confine: true
    },
    xAxis: {
      type: "category",
      boundarGap: false,
      data:
        obj && obj.pointValues.length > 0
          ? obj.pointValues.map(item => formatDate(item.time))
          : ["11:00", "12:00", "13:00", "14:00", "15:00", "16:00"]
    },
    yAxis: yAxis,
    series: series
  };
  weatherOptions.value = option;
};

// 重置筛选条件
const resetSpc = async () => {
  dateRangeSpcDetail.value = initSpcDate();
  spcJobList.value = [weatherSpcJobList.value.filter(item => item.itemValue === "WEATHER_TEMP_DRY")[0].itemDesc];
  querySpc();
};

// 点击点位展示图表
const pointClick = async (row: any) => {
  if (!isClick.value) {
    return;
  }
  console.log(isActiveBtns.value, "------------------------");
  lineChartLoading.value = true;
  isClick.value = false;
  showCharts.value = true;
  let list = [];
  const param = getParams.value;
  const currentIndex = isActiveBtns.value.indexOf(row.point);
  console.log(currentIndex, isActiveBtns.value, "能否找到-1 找不到 非-1 能找到");
  if (currentIndex !== -1) {
    isActiveBtns.value.splice(currentIndex, 1);
  } else {
    isActiveBtns.value.push(row.point);
  }
  if (isActiveBtns.value.length) {
    for (let i = 0; i < isActiveBtns.value.length; i++) {
      const str1 = isActiveBtns.value[i];
      const params = {
        panelCode: "cr_heatmap",
        criteria: {
          timespan: Detail.value.testCompany,
          startTime: dateRangeSpc.value[0],
          endTime: dateRangeSpc.value[1],
          // startTime: "2024-09-13 11:40:00",
          // endTime: "2024-09-15 12:13:24",
          points: [str1]
        }
      };
      try {
        await queryHeatMap(params, list, param, row);
      } catch (error) {
        lineChartLoading.value = false;
        isClick.value = true;
      }
    }
    nextTick(() => {
      lineChartLoading.value = false;
      isClick.value = true;
    });
  } else {
    // 清空图表
    lineChartLoading.value = false;
    isClick.value = true;
    heatMapOptions.value = {};
    linesOptions.value = {};
    midKey.value = Date.now();
  }
};

const editSpcY2 = () => {
  getWeatherData();
  visibleY2.value = false;
};

const getPIDdata = async () => {
  const pidData: any = await getPID({ ...getParams.value });
  console.log(pidData, "pidData");
  upDownData.value = pidData;
};

const formatDate = timestamp => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  const s = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${h}:${m}:${s}`;
};

const tabSelectHandler = async (selectName: string) => {
  activeName.value = selectName;
  await switchTabsChangeHandler();
};

const amcBtnData = computed(() => {
  return amcData.value.map(item => {
    return {
      point: getPoint(item.itemName, upDownData.value),
      ...item
    };
  });
});
const particleBtnData = computed(() => {
  return particleData.value.map(item => {
    return {
      point: getPoint(item.itemName, upDownData.value),
      ...item
    };
  });
});

onMounted(async () => {
  queryBtnLoading.value = true;
  await getWeatherNow();
  dateRangeSpc.value = initDate(mins.value);
  const amcData1: any = await queryChildByTypeCodeAndItemValue({
    value: "CIT01",
    typeCode: "MCTS"
  });
  amcData.value = amcData1.map(item => {
    return {
      type: JSON.parse(item.itemDesc).attr,
      ...item
    };
  });
  targetList3.value = amcData.value.map(e => e.type);
  // particle 洁净指标
  const particleData1: any = await queryChildByTypeCodeAndItemValue({
    value: "CIT03",
    typeCode: "MCTS"
  });
  particleData.value = particleData1.map(item => {
    return {
      type: JSON.parse(item.itemDesc).attr,
      ...item
    };
  });
  targetList2.value = particleData.value.map(e => e.type);
  // 温湿度-环境指标
  const environData1: any = await queryChildByTypeCodeAndItemValue({
    value: "CIT04",
    typeCode: "MCTS"
  });
  environData.value = environData1.map(item => {
    return {
      type: JSON.parse(item.itemDesc).attr,
      ...item
    };
  });
  targetList.value = environData.value.map(e => e.type);
  // MAU-设备指标
  const eqpData1: any = await queryChildByTypeCodeAndItemValue({
    value: "CIT05",
    typeCode: "MCTS"
  });
  eqpData.value = eqpData1.map(item => {
    return {
      type: JSON.parse(item.itemDesc).attr,
      ...item
    };
  });
  const res: any = await queryChildByTypeCodeAndItemValue({
    typeCode: "OUTDOOR_WEATHER"
  });
  weatherSpcJobList.value = res;
  spcJobList.value = [weatherSpcJobList.value.filter(item => item.itemValue === "WEATHER_TEMP_DRY")[0].itemDesc];
  // getWeatherData();
  // 通过厂区字典查询区域
  const codes: any = await queryChildByTypeCodeAndItemValue({
    value: "CR_ALL_CODES",
    typeCode: "MCTS"
  });
  const id = JSON.parse(codes.filter(item => item.itemValue === "CR_POSITION_CODE")[0].itemDesc)[0].facCode; // 暂时写死一期厂区
  await queryAreaList(id);
  await switchTabsChangeHandler();
  // await getHotPointes();
  await getPIDdata();
  if (JSON_DATA.value[currentArea.value] && JSON_DATA.value[currentArea.value].length) {
    getPointListNewValue(JSON_DATA.value[currentArea.value].map(e => e.point));
  }
});

onUnmounted(() => {
  useCancelUpdateDomHeight();
});
</script>

<style lang="scss" scoped>
.page-main {
  display: flex;
  gap: 16px;
  justify-content: space-between;
  width: 100%;
  min-width: 1300px;
  height: 268px;

  .header_box {
    display: flex;
    flex-flow: column;
    gap: 14px;
    width: 100%;
    padding: 16px 24px;
    background-color: white;
    border-radius: 4px;

    .custom-form-ui {
      display: flex;
      align-items: center;

      .spc_target {
        min-width: 495px;
        margin-right: 16px;
      }

      .px-form-item {
        margin-bottom: 0;
      }
    }

    .top_box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;

      .weather_con {
        display: flex;
        flex: 1;
        flex-flow: column wrap;
        gap: 4px;
      }

      .right_btn {
        display: flex;
        justify-content: end;
      }

      :deep(.weather-list) {
        gap: 8px;
        justify-content: space-between;
      }

      :deep(.weather-list-item) {
        margin-right: 0;
      }
    }

    .top-con-check {
      display: flex;
      flex-flow: row wrap;
      width: 100%;
      height: auto;

      .check-btn-item {
        display: flex;
        flex-flow: row nowrap;
        gap: 8px;
        align-items: center;
        justify-content: flex-start;
        // width: 100%;
        height: 30px;
        margin-right: 16px;

        .check-title {
          height: 20px;
          font-size: 14px;
          font-weight: 600;
          line-height: 20px;
          text-align: left;
        }
      }
    }

    .switch_box {
      width: 100%;

      .switch_tabs {
        display: flex;
        flex-flow: row nowrap;
        gap: 12px;
        align-items: center;
        justify-content: flex-start;

        .switch_item {
          font-size: 14px;
          text-align: center;
          cursor: pointer;
          border: 1px solid #dcdcdc;
          border-radius: 3px;

          &:hover {
            border: 1px solid #3b82f6;
          }
        }

        .activeClass {
          position: relative;
          font-size: 14px;
          text-align: center;
          cursor: pointer;
          border: 1px solid #3b82f6;
          border-radius: 3px;

          // &::after {
          //   position: absolute;
          //   top: 100%;
          //   left: 50%;
          //   width: 0;
          //   height: 0;
          //   content: "";
          //   border: 8px solid transparent;
          //   border-top-color: #3b82f6;
          //   transform: translate(-50%);
          // }
        }

        .item_name {
          padding: 0 7px;
          white-space: nowrap;
          border-radius: 3px 3px 0 0;
        }

        .item_red {
          color: #fff;
          background-color: #ef4444;
          border-radius: 0 0 2px 2px;
        }

        .item_green {
          color: #fff;
          background-color: #10b981;
          border-radius: 0 0 2px 2px;
        }
      }
    }
  }

  .small_map {
    padding: 16px;
    background-color: #fff;
    border-radius: 4px;

    .map_img {
      width: 300px;
      height: 100%;
      // background-image: url("@/assets/svg/machine/build_img.png");
      background-repeat: no-repeat;
      background-position: center center;
      background-size: 100% 100%;
    }
  }

  .con_bar {
    .fab-tabs-fade-enter-active,
    .fab-tabs-fade-leave-active {
      transition: all 0.4s ease;
    }

    .fab-tabs-fade-enter-from {
      opacity: 0;
      transform: translateX(-80px);
    }

    .fab-tabs-fade-leave-to {
      opacity: 0;
      transform: translateX(80px);
    }
  }
}

.page-con {
  width: 100%;
  min-width: 1300px;
  padding: 16px 24px;
  margin-top: 16px;
  background-color: white;
  border-radius: 4px;
}

.page-con-img {
  display: flex;
  justify-content: space-between;
  width: 100%;
  min-width: 1300px;
  height: 532px;
  padding: 16px 0 16px 24px;
  margin-top: 16px;
  background-color: white;
  border-radius: 4px;

  .con-contro {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 30px;
    height: 100%;
  }

  .con-chart-tabs {
    width: 80%;
    min-width: 700px;
    height: 100%;
    border: 1px solid #ccc;

    .chart_con {
      width: 100%;
      height: calc(100% - 40px);

      .chart_item {
        width: 100%;
        height: 100%;
      }
    }

    :deep(.px-tabs__header) {
      background-color: #f5f5f5;
      border: none;
    }

    :deep(.px-tabs__nav) {
      margin: 0;
      border: none;
    }

    :deep(.px-tabs__item) {
      width: 118px;
      padding: 0 !important;
      text-align: center;
    }

    :deep(.is-active) {
      background-color: white;
      border-top: 4px solid #3b82f6;
    }
  }

  .con_left {
    // display: flex;
    // justify-content: center;
    min-width: 500px;
    height: 100%;
    // background-color: #f0f2f5;

    .con_img {
      width: 100%;
      // width: 500px;
      height: 100%;
      // object-fit: cover;
      // object-position: center;
      // height: 500px;
      // background-image: url("@/assets/svg/machine/build_img.png");
      background-repeat: no-repeat;
      background-position: center;
      background-size: cover;
      // left: 50%;
      // transform: translate(-50%);
    }

    .con_img_panel {
      position: absolute;
      top: 110px;
      right: 128px;
      min-width: 212px;
      min-height: 120px;
      padding: 8px;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 0 10px rgb(0 37 86 / 12%);

      .panel_box {
        width: 100%;
        height: 100%;
        border: 1px solid #dcdcdc;
      }

      .panel_con {
        display: flex;
        justify-content: space-between;
        width: 100%;
        height: 100%;
      }

      .panel_title {
        width: 100%;
        height: 24px;
        font-size: 12px;
        font-weight: bold;
        line-height: 24px;
        text-align: center;
        border-bottom: 1px solid #dcdcdc;
      }

      .panel_con_left {
        width: fit-content;
        height: 100%;
        padding: 2px;
        font-size: 12px;
      }

      .panel_con_right {
        width: fit-content;
        height: 100%;
        padding: 2px;
        font-size: 12px;
      }

      .con_list {
        display: flex;
        gap: 6px;
        width: 100%;

        .list_left {
          width: 40px;
          text-align: right;
        }

        .list_value {
          flex: 1;
          text-align: left;
        }
      }
    }

    .con_img_point {
      position: absolute;
      width: auto;
      cursor: pointer;
      // &:hover {
      //   z-index: 999;
      // }

      // &:hover .point_item {
      //   z-index: 999;
      // }
      // background-image: url("@/assets/svg/machine/warning.png");

      .point_item {
        display: flex;
        flex-flow: row nowrap;
        gap: 5px;
        align-items: center;
        width: auto;
        height: 24px;
        padding: 0 8px 0 3px;
        font-size: 12px;
        line-height: 24px;
        background-color: white;
        border-radius: 12px;
        box-shadow: 0 4px 12px 0 rgb(0 0 0 / 12%);

        &::after {
          position: absolute;
          top: 100%;
          left: 16px;
          width: 0;
          height: 0;
          content: "";
          border: 6px solid transparent;
          border-top-color: #fff;
          transform: translate(-50%);
        }

        .content-icon {
          width: 16px;
          height: 16px;
        }

        .point_name {
          white-space: nowrap;
        }

        .point_value {
          white-space: nowrap;
        }
      }

      .pop_text {
        font-size: 14px;
      }

      .no-click {
        pointer-events: none;
      }
    }
  }
}
</style>
